
import React, { Component } from 'react';
import {
  StyleSheet, Text, FlatList, Alert,
  PixelRatio, View, Image, TouchableOpacity, DeviceEventEmitter
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import HTTP from '../../../utils/http';
import { NavigationEvents } from 'react-navigation';
import ToastUtil from '../../../utils/toast';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { CommonDialog } from '../../../components/common/Dialog';
import OrderDetailsService from '../details/_common/service';
import { ProgressModal } from '../../../components/common/ProgressModal';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { NewAccountHome } from '../../../components/common/newAccountHome';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../imgs/sanjiao3.png')
const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { }
}

export class FeedContractPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '非业务合同审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      companyIndex: 0,
      tabIndex: 0,
      tabItem: 0,
      status: 'data',
      refreshIcon: false,
      listData: [],
      itemData: {},
      isTablet: true,
      cntList: true,
      isDataItem: true,
      itemAuditingletedCnt: '0',
      itemAuditRejectCntCnt: '0',
      totalPage: '0',
      dataList: '',
      previewModalVisible: false,
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
      },
      alertShow: false,
      options: [],
      choice: {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
    }
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }
    this.mackStr = '';
  }

  async componentDidMount() {
    // await this.getSorage();
    await this.initPage();
  }

  //获取业务组织
  // async  getSorage () {
  //   const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
  //   const userInfo = JSON.parse(userInfoJson);
  //   this.setState({
  //     options: userInfo.corpInfoTOs || [],
  //     choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
  //   })
  // }

  //初始化数据
  initPage = async (refreshIcon) => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
    }
    let resAll = await HTTP.POST(API_GENERATE(API.FEEd_AUDIT_LIST_MUL), this.params);
    console.log('resAll', resAll);
    if (resAll && resAll.length) {
      let res = resAll[this.state.companyIndex].paginationModel
      let options = resAll || [];
      options.map((item, index) => {
        item.rowCount = resAll[index].paginationModel.recordCount
      })
      if (res) {
        let responseData = res.rows;
        this.setState({
          listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
          status: responseData.length > 0 ? 'data' : 'empty',
          refreshIcon: false,
          totalPage: res.totalPage,
          options,
          choice: options[this.state.companyIndex] || {},
        })
        this.pageParams.pageNo = res.pageNo++;
      } else {
        this.setState({
          status: 'error'
        })
      }
    } else if (resAll.length == 0) {
      this.setState({
        status: 'empty'
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  loadMore = () => {
    if (this.state.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  refresh = () => {
    this.pageParams.pageNo = 1;
    if (this.state.totalPage >= this.pageParams.pageNo) {
      this.reload = false;
      this.initPage();
    }
  }


  _tabList = (items, tabItem) => {
    this.reload = true;
    this.pageParams.pageNo = 1;
    this.setState({
      tabItem,
      params: {
        applyType: items.params.applyType,
      },
      totalPage: '0',
    }, () => {
      this.pageParams.pageNo = 1;
      this.initPage();
    })

  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }

  // 同意
  auditPress = (type, item) => {
    this.auditResult = type;
    this.remark = '';
    if (item) {
      this.setState({
        showRejectModal: true,
        itemData: item,
      })
    } else {
      ToastUtil.showWarning('没有数据')
    }
  }

  // 审批
  approve = async () => {
    const data = this.state.itemData;
    let requestParams = {
      businessKey: data.businessKey,
      formKey: data.formKey,
      remark: this.remark,
      taskName: data.taskName,
      taskId: data.taskId,
      auditResult: this.auditResult,
      corpId: this.state.choice.corpId
    };
    let text = this.auditResult ? '审批' : '驳回';
    this.setState({
      showRejectModal: false,
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.FEEd_DEALAUDIT), requestParams);
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.reloadPage()
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }

  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.initPage();
  }

  // 查看附件
  goItemAppendix = async (item) => {

    let responseData1 = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: item }, { rejectError: false, handerError: true }, 30000);
    console.log(responseData1)
    if (responseData1.attachmentFileVO.fileExtName === 'pdf') {
      this.props.navigation.navigate('ContractPdfPage', { finalFileId: item, title: '附件信息', });
    } else if (responseData1.attachmentFileVO.fileExtName === 'jpg' || responseData1.attachmentFileVO.fileExtName === 'png' || responseData1.attachmentFileVO.fileExtName === 'jpeg' || responseData1.attachmentFileVO.fileExtName === 'bmp') {
      this.preview(item);
    } else {
      ToastUtil.showInfo(`抱歉，暂不支持${responseData1.attachmentFileVO.fileExtName}文件类型的预览～`)
    }
  }

  async preview(fileId) {
    const imgData = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId }, null, 30000);
    if (imgData && imgData.image) {
      let { image } = imgData;
      if (image && image.length) {
        modalPicDelCfg.visible = true;
        modalPicDelCfg.delTextHide = true; //隐藏删除
        modalPicDelCfg.uri = image;
        modalPicDelCfg.attachmentModalStyle = { backgroundColor: 'rgba(0,0,0,0)' };
        this.setState({
          previewModalVisible: true
        });
      }
    }
  }
  // 查看审批流
  _getCheckApprove = async (item) => {
    const { choice } = this.state;
    const { corpId } = choice || {};
    // this.setState({ status: 'loading' })
    //查询审批节点
    let responseData1 = await OrderDetailsService.checkApproval(item.businessKey, 'COST_CONTRACT', item.processInstanceId, corpId);
    console.log('2636636', responseData1)
    responseData1 = responseData1 && responseData1.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批状态';
    lightBoxData.rowDataList = responseData1;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }

  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }

  _approvalListItim = (data) => {
    let item = data.item;
    let iteArray = item.bizInfo.attachmentId && item.bizInfo.attachmentId.split(',');
    let { companyIndex, options } = this.state;
    let { corpName } = options[companyIndex] || {};
    return (
      <View style={{
        marginTop: 20 * scale, paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
      }}>
        <View style={styles.itemTimeData}>
          <Text style={[styles.itemLightText, { color: '#848A96' }]}>{item && item.bizInfo ? item.bizInfo.createTime : '--'}</Text>
        </View>
        <View activeOpacity={.6} style={styles.itemWrap} >
          <View style={styles.itemName}>
            <View style={{ alignItems: 'flex-start' }}>
              <Text style={styles.itemLightText}>{item && item.bizInfo ? item.bizInfo.costCompanyId : '--'}</Text>
            </View>
          </View>
          <View style={{ alignItems: 'flex-start' }}>
            <Text style={{ fontSize: 10 * scale, paddingBottom: 12 * scale, paddingLeft: 12 * scale, color: '#848A96' }}>(业务组织：{corpName || '-'})</Text>
          </View>
          <View style={styles.itemBorder}></View>
          <View style={{ marginBottom: 15 * scale, marginTop: 10 * scale, }}>
            <View style={styles.itemContent}>
              <Text style={styles.itemContractNumbers}>合同号</Text>
              <Text style={styles.itemContractNumber}>线下合同号</Text>
              <Text style={styles.ItemRemarks}>备注</Text>
            </View>
            <View style={styles.itemContent}>
              <Text style={styles.itemContractNames}>{item && item.bizInfo ? item.bizInfo.costContractId : '--'}</Text>
              <Text style={styles.itemContractName}>{item && item.bizInfo ? item.bizInfo.offlineContractCode : '--'}</Text>
              <Text style={styles.itemNumber} onPress={() => { this.mackStr = (item && item.bizInfo && item.bizInfo.remark) || '暂无数据'; this.setState({ modalVisible: true, }) }}>查看</Text>

            </View>

            <View style={styles.itemContentRemark}>
              <Text style={styles.itemContractNumbers}>有效时间</Text>
              <Text style={styles.itemContractNumber}>创建人</Text>
              <Text style={styles.ItemRemarks}></Text>
            </View>
            <View style={styles.itemContent}>
              <Text style={[styles.itemContractNames,]}>
                {item.bizInfo.contractBeginDate ? (item && item.bizInfo && item.bizInfo.contractBeginDate.length > 10 ? (item.bizInfo.contractBeginDate.substr(0, 11)) : item.bizInfo.contractBeginDate) : '--'}
                {item.bizInfo.contractEndDate ? (item && item.bizInfo && item.bizInfo.contractEndDate.length > 10 ? (item.bizInfo.contractEndDate.substr(0, 11)) : item.bizInfo.contractEndDate) : '--'}
              </Text>
              <Text style={[styles.itemOperateNames,]}>
                {item && item.bizInfo ? item.bizInfo.createrName : '--'}
              </Text>
            </View>
            <View style={styles.itemContract}>
              <Text style={styles.itemLightText}>合同附件</Text>
            </View>
            <View style={[styles.itemName, { flexWrap: 'wrap' }]}>
              {iteArray && iteArray.map((item, index) => {
                return (
                  <View style={styles.itemAccountNumber} key={index}>
                    <Text style={styles.itemAppendix} onPress={() => { this.goItemAppendix(item) }}>[附件{index + 1}]  </Text>
                  </View>
                )
              })
              }
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.itemDayTime}>
              <Text style={styles.itemApprovalFlow} onPress={() => { this._getCheckApprove(item) }}>[审批流]</Text>
              <Text style={[styles.consent, styles.consentColor]} onPress={() => { this.auditPress(1, item) }}>同意</Text>
              <Text style={styles.itemdown} onPress={() => { this.auditPress(0, item) }}>驳回</Text>
            </View>
          </View>
        </View>
      </View>
    )
  }

  _renderToastWrap = () => {
    return (
      <View>
        <View style={styles.textRow}>
          <Text style={styles.textRowText}>{this.mackStr || ''}</Text>
        </View>
      </View>
    )
  }

  render() {
    let { listData, refreshIcon, status, showRejectModal, modalVisible, alertShow, choice, options } = this.state;
    let { lightBoxData } = this.state || {};
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          // await this.getSorage();
          await this.initPage();
        }} />
        {options.length > 1 ?
          <NewAccountHome
            fn={(val) => {
              this.setState({ companyIndex: val }, () => {
                this.initPage();
              })
            }}
            options={options}
            choice={choice} />
          : null}
        <View style={[styles.stateView, styles.marginStyle]}>
        </View>
        {
          status == 'data' ? (
            (
              <View style={styles.body}>
                <FlatList
                  data={listData}
                  renderItem={
                    this._approvalListItim
                  }
                  refreshing={refreshIcon}
                  onRefresh={() => { this.refresh() }}
                  onEndReachedThreshold={1}
                  onEndReached={() => { this.loadMore() }}
                />
              </View>
            )
          ) : (<View style={{ flex: 1 }}>
            <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
          </View>)
        }
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        <CommonDialog modalVisible={modalVisible} title={'合同条款及收费标准'} renderCustom={
          this._renderToastWrap
        } onClosePress={() => { this.setState({ modalVisible: false }) }} />
        {/* 审批流 */}
        <ProgressModal {...lightBoxData} />
        <ModalPicDelComponent {...modalPicDelCfg} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  headBox: {
    backgroundColor: style.color.themeColor,
    height: 50 * scale,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  tabItems: {
    color: style.color.white,
    fontSize: 12 * scale,
    width: '35%',
    textAlign: 'center',
    marginTop: 20 * scale,
    opacity: .8
  },
  tabItemActive: {
    opacity: 1
  },
  stateView: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    backgroundColor: style.color.themeColor,
  },
  stateItem: {
    // paddingTop: 10 * scale,
    // paddingBottom: 10 * scale,
    // paddingLeft: 10 * scale,
    // paddingRight: 10 * scale,
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor,
    fontWeight: '500',
  },
  stateItemInfo: {
    width: 5 * scale,
    height: 5 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateActive: {
    backgroundColor: style.color.white,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  body: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#272727',
    fontWeight: '500',
  },
  itemTimeData: {
    marginBottom: 7 * scale,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    // justifyContent: 'flex-end',
    flexDirection: 'row',
    position: 'relative',
    alignItems: 'center',
    paddingLeft: 12 * scale,
    // flex: 1,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginLeft: 130 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  consentColor: {
    // backgroundColor: style.color.themeColor,
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    position: 'relative',
    marginLeft: 10 * scale,
  },
  itemTime: {
    flexDirection: 'row',
    flex: 1,
  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 8 * scale,
    marginTop: 6 * scale,
    // paddingLeft: 12 * scale,
    // paddingRight: 12 * scale,
    // paddingBottom: 14 * scale,
    paddingTop: 14 * scale,
  },
  itemType: {
    flex: 4
  },
  itemLightColor: {
    // justifyContent: 'flex-end',
    fontSize: 12 * scale,

    // marginRight: 16 * scale,
    color: '#F60202',
    fontWeight: '500',
  },
  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  itemName: {
    flexDirection: 'row',
    marginBottom: 15 * scale,
    marginTop: 5 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  itemContract: {
    flexDirection: 'row',
    // marginBottom: 15 * scale,
    marginTop: 5 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  itemContent: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
    marginBottom: 15 * scale,
    paddingLeft: 12 * scale,
  },
  itemContentRemark: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
    marginBottom: 12 * scale,
    paddingLeft: 12 * scale,
    paddingTop: 20 * scale,
  },
  itemContractNumber: {
    color: '#000000',
    fontSize: 12 * scale,
    flex: 4,
    paddingLeft: 15 * scale
  },
  itemContractNumbers: {
    color: '#000000',
    fontSize: 12 * scale,
    flex: 3.5,
  },
  itemContractName: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 4,
    paddingLeft: 15 * scale
  },
  itemOperateNames: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 6.5,
    paddingLeft: 15 * scale
  },
  itemContractNames: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 3.5
  },
  ItemRemarks: {
    color: '#000000',
    fontSize: 12 * scale,
    flex: 2.5,
    paddingLeft: 5 * scale,
  },
  arrowIcon: {

    position: 'absolute',
    right: 0,
    top: 2 * scale,
    right: 32 * scale,
  },
  itemApplyAmount: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingRight: 10 * scale,
  },
  itemNumber: {
    // color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 2.5,
    paddingLeft: 5 * scale,
    color: '#0087FF'
  },
  itemApprovalFlow: {

    justifyContent: 'flex-start',
    color: '#0087FF',
    fontWeight: '600'
  },
  textRow: {
    marginBottom: 20 * scale
  },
  textRowText: {
    paddingLeft: 15 * scale
  },
  itemAccountNumber: {
    marginRight: 12 * scale
  },
  itemAppendix: {
    fontSize: 12 * scale,
    fontWeight: '600',
    color: '#0087FF',
    width: 50 * scale,
    marginTop: 10 * scale,
  },
  accountSelect: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  }
})